package com.mobilesales.android.activities.tasks;

import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.mobilesales.android.R;
import com.mobilesales.android.activities.ListModelActivity;
import com.mobilesales.android.adapters.TaskAdapter;
import com.mobilesales.android.database.TaskManager;
import com.mobilesales.android.model.tasks.CyclicTask;
import com.mobilesales.android.model.tasks.Schedule;
import com.mobilesales.android.model.tasks.Task;
import com.mobilesales.android.util.Constants;
import com.mobilesales.android.util.DateUtil;
import com.mobilesales.android.util.MessageBox;
import com.mobilesales.android.util.Settings;


public class ListTask extends ListModelActivity<Task> {

	private TextView currentDateField;
	private TextView currentMonthShortField;
	private Button mapBtn;
	
	private List<Task> tasksOfDay;
	private Date selectedDate;
	private TaskAdapter itemsAdapter;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_list);
		currentDateField = (TextView) this.findViewById(R.id.currentDate);
		currentMonthShortField = (TextView)this.findViewById(R.id.currentMonthShort);
		mapBtn = (Button)this.findViewById(R.id.mapBtn);
		
		Bundle bundle = this.getIntent().getExtras();
		if (bundle != null && bundle.containsKey(Constants.SelectedDate)) {
			selectedDate = (Date) bundle.get(Constants.SelectedDate);
			Log.i("selectedDate", selectedDate.toLocaleString());
			currentDateField.setText(String.valueOf(selectedDate.getDate()));
			int[] monthNameResIds = DateUtil.monthNamesStringResourceIds();
			String monthName = getString(monthNameResIds[selectedDate.getMonth()]);
			currentMonthShortField.setText(monthName.substring(0, 3));
			
			loadItems();
		} else {
			MessageBox.show(this, getString(R.string.ErrorTaskList));
			finish();
		}
	}

	private void loadItems() {
		tasksOfDay = this.getItems();
		if (tasksOfDay != null) {
			if (tasksOfDay.size() > 0)
				mapBtn.setEnabled(true); 
			this.setItemsSource(tasksOfDay);
		} else {
			MessageBox.show(this, getString(R.string.ErrorTaskList));
			finish();
		}
	}

	@Override
	protected void onListItemClick(ListView listView, View view, int position,
			long id) {
		super.onListItemClick(listView, view, position, id);
		Task task = itemsAdapter.getItem(position);
		boolean isCyclicTask = (task instanceof CyclicTask);
		Intent intent = new Intent(this, DetailsTask.class);
		intent.putExtra(Constants.TaskId, task.Id);
		intent.putExtra(Constants.IsCyclicTask, isCyclicTask);
		this.startActivityForResult(intent, 0);
	}

	private List<CyclicTask> getCyclicTasks(Date currentDate) {
		Log.i("currentDate", currentDate.toLocaleString());
		TaskManager manager = new TaskManager(this);
		List<CyclicTask> tasks = manager.GetCyclicTaskList(Settings
				.getSettings().getEmployeeId());
		manager.Close();
		
		List<CyclicTask> taskInTime = null;
		if (tasks!=null) {
			taskInTime = new ArrayList<CyclicTask>();
	    	GregorianCalendar calendar = new GregorianCalendar();
	    	for(CyclicTask tsk : tasks) {
    			Date date = DateUtil.parseDate(tsk.StartTime);
    			calendar.setTime(date);
    	    	GregorianCalendar current = new GregorianCalendar();
    	    	current.setTime(currentDate);
    			current.set(GregorianCalendar.HOUR_OF_DAY, calendar.get(GregorianCalendar.HOUR_OF_DAY));
    			current.set(GregorianCalendar.MINUTE, calendar.get(GregorianCalendar.MINUTE));
    			
    			Log.i("Current", current.getTime().toLocaleString());
    			Log.i("Day", calendar.getTime().toLocaleString());
    			
    			long diff = Math.abs(current.getTimeInMillis() - calendar.getTimeInMillis())
    						 			/ (24 * 60 * 60 * 1000);
    			
    			Log.i("diff",diff+"");
    			Log.i("taskInterval",tsk.TaskInterval+"");
    			Log.i("diff % tsk.TaskInterval",(diff % tsk.TaskInterval)+"");
    			
    			if (diff % tsk.TaskInterval == 0)        			
    				taskInTime.add(tsk);
    		}	
			Log.i("MobileSales", "taskInTime:"+taskInTime.size());
	    	
		}
		return taskInTime;
	}

	private List<Task> getTasks(Date date) {
		List<Task> tasks = null;
		TaskManager manager = new TaskManager(this);
		List<Schedule> schedules = manager.GetScheduleList(Settings.getSettings().getEmployeeId());
		if (schedules !=null) {
			tasks = new ArrayList<Task>();
			for(Schedule s : schedules) {
				List<Task> stasks = manager.GetTaskList(s.Id);
				if (stasks!=null) {
					tasks.addAll(stasks);
				}
				else {
					tasks = null;
					break;
				}
			}
		}
		manager.Close();
		if (tasks != null) {
			List<Task> incorrect = new ArrayList<Task>();
			for (Task t : tasks) {
				String currentDate = DateUtil.toShortDateString(date);
				String taskDate = t.StartTime.split(" ")[0];
				if (!currentDate.equals(taskDate)) {
					incorrect.add(t);
				}
			}
			for (Task t : incorrect)
				tasks.remove(t);
		}
		return tasks;
	}

	public void addTask(View v) {
		Intent intent = new Intent(this, StoreTask.class);
		intent.putExtra(Constants.IsCyclicTask, false);
		intent.putExtra(Constants.SelectedDate, this.selectedDate);
		this.startActivityForResult(intent, 0);
	}
	
	public void showMap(View v) {
		Intent intent = new Intent(this, TaskMap.class);
		intent.putExtra(Constants.SelectedDate, this.selectedDate);
		this.startActivityForResult(intent, 0);
	}

	public void addCyclicTask(View v) {
		Intent intent = new Intent(this, StoreTask.class);
		intent.putExtra(Constants.IsCyclicTask, true);
		intent.putExtra(Constants.SelectedDate, this.selectedDate);
		this.startActivityForResult(intent, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		this.loadItems();
	}

	public void finish(View v) {
		finish();
	}

	public void refresh() {
		getHandler().post(new Runnable() {
			public void run() {
				loadItems();
			}
		});
	}

	@Override
	protected void setItemsSource(List<Task> source) {
		itemsAdapter = new TaskAdapter(this, R.layout.task_list_item,
				source);
		this.setListAdapter(itemsAdapter);
	}

	@Override
	protected List<Task> getItems() {
		if (this.selectedDate != null) {
			List<Task> tasks = getTasks(selectedDate);
			List<CyclicTask> cyclicTasks = getCyclicTasks(selectedDate);
			List<Task> tasksOfDay = new ArrayList<Task>();
			if (tasks != null && cyclicTasks != null) {
				for (Task tsk : tasks)
					tasksOfDay.add(tsk);
				for (CyclicTask tsk : cyclicTasks)
					tasksOfDay.add(tsk);
				return tasksOfDay;
			}
		}
		return null;
	}
}
